package com.sam.mvp.presenter;

import android.annotation.SuppressLint;
import android.app.Application;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.OnLifecycleEvent;

import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import okhttp3.ResponseBody;

import javax.inject.Inject;

import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.sam.api.EvenBusTag;
import com.sam.mvp.entity.User;
import com.sam.mvp.contract.MainContract;
import com.sam.mvp.ui.adapter.MainAdapter;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.List;


@ActivityScope
public class MainPresenter extends BasePresenter<MainContract.Model, MainContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    MainAdapter mAdapter;

    @Inject
    List<User> mUsers;

    private int sinceNum = 1; // 默认第一页
    private boolean pullToRefresh = true;

    @Inject
    public MainPresenter(MainContract.Model model, MainContract.View rootView) {
        super(model, rootView);
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate() {
        getUserData(true);//打开 App 时自动加载列表
    }

    private int preEndIndex = 0;

    public void getUserData(boolean pullToRefresh) {
        mModel.getUsers(sinceNum, pullToRefresh)
                .observeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> {
                    //开始加载
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //结束加载
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView)) // 添加presenter周期和activity一样 同时销毁
                .subscribe(new ErrorHandleSubscriber<List<User>>(mErrorHandler) { //添加错误消息监听
                    @SuppressLint("NewApi")
                    @Override
                    public void onNext(List<User> users) {
                        sinceNum = users.get(users.size() - 1).id;
                        mUsers.addAll(users);
                        mRootView.showTextContent(mUsers);
                        if (preEndIndex == 0) {
                            mAdapter.notifyDataSetChanged();
                        } else {
                            preEndIndex = mUsers.size();
                            mAdapter.notifyItemChanged(preEndIndex, users.size());
                        }


                    }
                })
        ;
    }

    @SuppressLint("NewApi")
    public void downLoadImg(String url) {

        Observable<ResponseBody> xx = mModel.downloadFile(url);
        xx.observeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .subscribeOn(Schedulers.newThread())
                .map(responseBody -> responseBody.string())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView)) // 添加presenter周期和activity一样 同时销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onNext(String s) {
                    }
                });


    }

    @Subscriber(tag = EvenBusTag.GOTO_EVENTBUS, mode = ThreadMode.ASYNC)
    public void onEvent(String s) {
        ArmsUtils.snackbarText(s);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.mAdapter = null;
        this.mUsers = null;
    }
}
